<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="80px"
    >
      <el-form-item label="子墨编号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入子墨订单编号"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="系统编号" prop="sysOrderNo">
        <el-input
          v-model="queryParams.sysOrderNo"
          placeholder="请输入系统编号"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="芯片链接" prop="chipLink">
        <el-input
          v-model="queryParams.chipLink"
          placeholder="请输入芯片链接"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户名称" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入客户名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="签订日期">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="exported">
        <el-select
          v-model="queryParams.exported"
          placeholder="订单状态"
          clearable
          style="width: 240px"
        >
          <el-option label="全部" value="" />
          <el-option label="未导出" :value="0" />
          <el-option label="已导出" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleImport"
          v-hasPermi="['order:import']"
          >导入</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['order:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList">
      <el-table-column
        v-for="(val, key) in tableInfo"
        :key="key"
        :label="val.title"
        align="center"
        :prop="val.value"
        :width="val.width"
      >
        <template #default="scoped" v-if="val.render">
          {{ val.render(scoped) }}
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOrder, orderDown } from "@/api/order";
import { getToken } from "@/utils/auth";
import { parseTime } from "@/utils/ruoyi";
import { Message, Loading } from "element-ui";
import { blobValidate } from "@/utils/ruoyi";
import { saveAs } from "file-saver";
export default {
  name: "Order",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单表格数据
      orderList: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        chipLink: "",
        customerName: "",
        endSignDate: "",
        filterExported: true,
        isAsc: "",
        orderByColumn: "",
        orderNo: "",
        pageNum: 0,
        pageSize: 10,
        startSignDate: "",
        sysOrderNo: "",
        exported: "",
      },
      upload: {
        open: false,
        title: "",
        isUploading: false,
        headers: { Authorization: "Bearer " + getToken() },
        url: process.env.VUE_APP_BASE_API + "/order/import",
      },
      exportedStatus: ["未导出", "已导出"],
      tableInfo: [
        {
          title: "订单编号",
          value: "sysOrderNo",
          width: 200,
        },
        {
          title: "芯片链接",
          value: "chipLink",
          width: 200,
        },
        {
          title: "门扇总数",
          value: "doorsNum",
        },
        {
          title: "对接工厂",
          value: "dockingPlant",
        },
        {
          title: "客户组别",
          value: "customerGroup",
        },
        {
          title: "订单类别",
          value: "orderCategory",
        },
        {
          title: "系列名称",
          value: "seriesName",
        },
        {
          title: "子墨订单编号",
          value: "orderNo",
          width: 150,
        },

        {
          title: "生产单号",
          value: "productionNo",
        },
        {
          title: "用户名称",
          value: "userName",
        },
        {
          title: "签订日期",
          value: "signTime",
        },
        {
          title: "客户名称",
          value: "customerName",
        },
        {
          title: "订单总金额",
          value: "totalAmount",
          width: 150,
        },
        {
          title: "实收金额",
          value: "fundsReceived",
        },
        {
          title: "其他费用",
          value: "otherExpenses",
        },
        {
          title: "应收金额",
          value: "amountReceivable",
        },
        {
          title: "状态",
          value: "status",
        },
        {
          title: "颜色",
          value: "color",
        },
        {
          title: "备注",
          value: "remark",
        },
        {
          title: "编制",
          value: "organization",
        },

        {
          title: "空套",
          value: "emptySleeves",
        },
        {
          title: "正在编辑",
          value: "editing",
        },
        {
          title: "排产日期",
          value: "schedulingDate",
        },
        {
          title: "入库状态",
          value: "storageStatus",
        },
        {
          title: "入库日期",
          value: "storageTime",
        },
        {
          title: "生产审核",
          value: "productionAudit",
        },
        {
          title: "发货状态",
          value: "shippingStatus",
        },
        {
          title: "最后发货",
          value: "finalDelivery",
        },
        {
          title: "最后收款",
          value: "finalCollection",
        },
        {
          title: "已结算",
          value: "settlement",
        },
        {
          title: "工厂结算总金额",
          value: "settlementAmount",
        },
        {
          title: "已结算日期",
          value: "settlementTime",
        },
        {
          title: "省",
          value: "province",
        },

        {
          title: "订单详情截图",
          value: "detailScreenshot",
        },
        {
          title: "状态",
          value: "exported",
          render: ({ row }) => {
            return this.exportedStatus[row.exported];
          },
        },
      ],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询订单类型列表 */
    getList() {
      this.loading = true;
      listOrder({
        ...this.queryParams,
        startSignDate:
          this.dateRange && parseTime(this.dateRange[0], "{y}-{m}-{d}"),
        endSignDate:
          this.dateRange && parseTime(this.dateRange[1], "{y}-{m}-{d}"),
      }).then((response) => {
        this.orderList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 表单重置
    reset() {
      this.form = {
        dictId: undefined,
        dictName: undefined,
        dictType: undefined,
        status: "0",
        remark: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "订单导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      if (response.code == 200) {
        response.msg = "导入成功";
      }
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 导出按钮操作 */
    handleExport() {
      let downloadLoadingInstance = Loading.service({
        text: "正在下载数据，请稍候",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      orderDown({
        ...this.queryParams,
        startSignDate:
          this.dateRange && parseTime(this.dateRange[0], "{y}-{m}-{d}"),
        endSignDate:
          this.dateRange && parseTime(this.dateRange[1], "{y}-{m}-{d}"),
      })
        .then(async (data) => {
            let time = parseTime(new Date(), "{y}-{m}-{d}")
            if(this.dateRange && this.dateRange[0] &&  this.dateRange[1]){
                time  = parseTime(this.dateRange[0], "{y}-{m}-{d}") + ' ~ ' + parseTime(this.dateRange[1], "{y}-{m}-{d}")
            }
          let isBlob = blobValidate(data);
          if (isBlob) {
            const blob = new Blob([data]);
            saveAs(blob, `芯片地址(${time}).xls`);
          } else {
            const resText = await data.text();
            const rspObj = JSON.parse(resText);
            const errMsg =
              errorCode[rspObj.code] || rspObj.msg || errorCode["default"];
            Message.error(errMsg);
          }
          downloadLoadingInstance.close();
        })
        .catch((r) => {
          console.error(r);
          Message.error("下载文件出现错误，请联系管理员！");
          downloadLoadingInstance.close();
        });
    },
  },
};
</script>
